package com.wolfking.converter.transform.base;


import com.google.common.collect.Lists;
import com.wolfking.converter.transform.FieldTransform;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class ByteArray2FieldTransform implements FieldTransform<Byte[]> {


    @Override
    public boolean canTransform(Class<?> fieldType) {
        return Byte[].class.equals(fieldType);
    }

    @Override
    public Byte[] transform(Object value) {
        byte[] bytes = null;

        if (value instanceof String) {
            bytes = ((String) value).getBytes(StandardCharsets.UTF_8);
        } else if (value instanceof byte[]) {
            bytes = (byte[]) value;
        } else if (value instanceof Byte[]) {
            return (Byte[]) value;
        } else if (value instanceof InputStream) {
            List<Byte> list = Lists.newArrayList();
            InputStream inputStream = (InputStream) value;
            byte[] buffer = new byte[2048];
            int readBytes;
            try {
                while ((readBytes = inputStream.read(buffer)) > 0) {
                    for (int i = 0; i < readBytes; i++) {
                        list.add(buffer[i]);
                    }
                }
                return list.toArray(new Byte[]{});
            } catch (Exception e) {
                log.warn("", e);
            } finally {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.debug("", e);
                }
            }
        }

        if (bytes == null) {
            bytes = value.toString().getBytes(StandardCharsets.UTF_8);
        }

        Byte[] copy = new Byte[bytes.length];
        System.arraycopy(bytes, 0, copy, 0, bytes.length);
        return copy;
    }
}
